﻿using System;
using System.Collections.Generic;
using System.Linq;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Synchronization.Validation.Internals
{
    public static class TypeChecker
    {
        public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic)
        {
            if (generic == toCheck || toCheck.IsGenericType)
            {
                return false;
            }

            while (toCheck != null && toCheck != typeof(object))
            {
                var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
                if (generic == cur)
                {
                    return true;
                }

                toCheck = toCheck.BaseType;
            }

            return false;
        }


        public static bool ImplementsInterface(this Type toCheck, Type interfaceType)
        {
            return toCheck.GetInterfaces().Contains(interfaceType);
        }
    }


    public static class RulesActivator
    {
        public static IEnumerable<RuleMetadata> CreateRuleInstances()
        {
            var assembly = typeof(Rule<>).Assembly;

            var types = assembly.GetTypes().Where(t => t.IsSubclassOfRawGeneric(typeof(Rule<>)));

            foreach (var type in types)
            {
                yield return (RuleMetadata)Activator.CreateInstance(type, null);
            }
        }
    }
}
